# 线程锁的基本使用 start
# from threading import Thread,Lock,Condition
# lock = Lock()
# def task(name,count):
#     for i in range(count):
#         lock.acquire()
#         print(f"{name}-step1-{i}\n",end='')
#         print(f"{name}-step2-{i}\n",end='')
#         print(f"{name}-step3-{i}\n",end='')
#         lock.release()
# thread01 = Thread(target=task,args=('AAA',3))
# thread02 = Thread(target=task,args=('BBB',3))
# thread03 = Thread(target=task,args=('CCC',3))
# thread01.start()
# thread02.start()
# thread03.start()
# 线程锁的基本使用 end


# 使用线程锁实现简化线程安全队列 start
from threading import Thread, Lock, Condition
import time


class MySafeQueue():
    def __init__(self, len):
        super().__init__()
        self.len = len
        self.__queue = list()
        self.__lock = Condition()

    def put(self, item):
        with self.__lock:
            while len(self.__queue) >= self.len:
                self.__lock.wait()
            self.__queue.insert(0, item)

    def get(self):
        with self.__lock:
            while len(self.__queue) == 0:
                self.__lock.wait()
            res = self.__queue.pop()
            self.__lock.notify_all()
            return res


queue = MySafeQueue(5)


class producer(Thread):
    def __init__(self, name, count, queue):
        super().__init__()
        self.name = name
        self.count = count
        self.queue = queue

    def run(self) -> None:
        for i in range(self.count):
            msg = f"{self.name}-{i}"
            self.queue.put(msg)


class consumer(Thread):
    def __init__(self, name, queue):
        super().__init__()
        self.name = name
        self.queue = queue
        self.daemon = True

    def run(self) -> None:
        while True:
            time.sleep(0.2)
            msg = self.queue.get()
            print(f"{self.name}-{msg}\n", end='')


threads = list()
threads.append(producer('producer01', 30, queue))
threads.append(producer('producer02', 30, queue))
threads.append(consumer('consumer01', queue))
threads.append(consumer('consumer02', queue))
for thread in threads:
    thread.start()
# 使用线程锁实现简化线程安全队列 end
